define(function(require,exports,module){
   'use strict';

    var React = require('react');
    var Highcharts = require('highcharts');
    var async = require('async');

    module.exports = React.createClass({displayName: "exports",
        getInitialState:function(){
            return {
                url:this.props.url,
                ajax_data:this.props.ajax_data,
                category:[],
                serias:[]
            };
        },
        componentDidMount:function(){
            var url = this.state.url;
            var data = this.props.ajax_data;

            var options = {
                colors: [
                    '#058DC7',
                    '#50B432',
                    '#ED561B',
                    '#DDDF00',
                    '#24CBE5',
                    '#64E572',
                    '#FF9655',
                    '#FFF263', 
                    '#6AF9C4'
                ], 
                chart: {
                    renderTo: this.props.id,
                    type: 'spline'
                },
                title: {
                    text: this.props.title
                },
                subtitle: {
                    text: this.props.description
                },
                xAxis: {
                    categories: this.state.category
                },
                yAxis: {
                    title: {
                        text: this.props.y
                    }
                },
                tooltip: {
                    formatter:function(){
                        var s = '<b>' + this.x + '</b>';

                        $.each(this.points, function () {
                            s += '<br/><span style="color:'+this.series.color+'">' + this.series.name + '</span>: ' +
                                Highcharts.numberFormat(this.y,0,'.',',');
                        });

                        return s;

                        //return '【'+this.x+'】'+ this.series.name + ':' + Highcharts.numberFormat(this.y,'0','.',',');
                    },
                    crosshairs: true,
                    shared: true
                },
                plotOptions: {
                    spline: {
                        lineWidth: 4,
                        states: {
                            hover: {
                                lineWidth: 5
                            }
                        },
                        marker: {
                            enabled: true
                        }
                    }
                },
                series: this.state.series,
                navigation: {
                    menuItemStyle: {
                        fontSize: '10px'
                    }
                }
            };

            var chart = new Highcharts.Chart(options);


            var get_ajax_data = function(){
                var tmp = [];

                var date = new XDate().addDays(-10).toString("yyyyMMdd");
            
                // var tianqi_sql = "SELECT count(*) as value,\
                //             thedate as name\
                //             FROM qeeniao.access_log\
                //             where thedate >= "+date+" and param_from = 'tianqi'\
                //             group by name\
                //             order by name ASC";

                var ku6_sql = "SELECT count(*) as value,\
                            thedate as name\
                            FROM qeeniao.access_log\
                            where thedate >= "+date+" and param_from = 'ku6'\
                            group by name\
                            order by name ASC";

                // var other_sql = "SELECT count(*) as value,\
                //             thedate as name\
                //             FROM qeeniao.access_log\
                //             where thedate >= "+date+" and param_from = ''\
                //             group by name\
                //             order by name ASC";

                async.waterfall([
                    function(done){
                        var cate_sql;
                        cate_sql = "SELECT distinct param_from FROM qeeniao.access_log where param_from <> ''";
                        $.ajax({
                            url:url,
                            data:{'sql':cate_sql,'access_token':data.access_token},
                            type:'post',
                            dataType:'json',
                            success:function(o){
                                done(null,o);
                            },
                            error:function(xhr,status,err){
                                console.error('获取数据失败！',status,err.toString());
                            }
                        });

                    },
                    function(cate,done){
                        var catetory_data = [];

                        if(cate.length > 0){
                            // cate.forEach(function(v,k){
                            //     catetory_data[v.param_from] = [];
                            // });

                            //类同步
                            async.map(cate,function(v,callback){
                                var sql = "SELECT count(*) as value,\
                                    thedate as name\
                                    FROM qeeniao.access_log\
                                    where thedate >= "+date+" and param_from = '"+v.param_from+"'\
                                    group by name\
                                    order by name ASC";

                                $.ajax({
                                    url:url,
                                    data:{'sql':sql,'access_token':data.access_token},
                                    type:'post',
                                    dataType:'json',
                                    success:function(o){
                                        var tmp = {'name':v.param_from,'data':o};
                                        // tmp[v.param_from] = o;
                                        callback(null,tmp);
                                    },
                                    error:function(xhr,status,err){
                                        console.error('获取数据失败！',status,err.toString());
                                    }
                                });
                            },function(err,result){
                                done(null,result);
                            });
                        }
                    }],function(error,result){
                        var category = [];
                        var series = [];

                        if(result.length > 0){
                            result.map(function(item){
                                if(item.data.length > 0){
                                    item.data.map(function(i){
                                        category.push(i.name);
                                    });
                                }
                            });
                        }

                        //获取全部横坐标值
                        var unique = function(o){
                            var n = {},r=[]; //n为hash表，r为临时数组
                            for(var i = 0; i < o.length; i++) //遍历当前数组
                            {
                                if (!n[o[i]]) //如果hash表中没有当前项
                                {
                                    n[o[i]] = true; //存入hash表
                                    r.push(o[i]); //把当前数组的当前项push到临时数组里面
                                }
                            }
                            return r;
                        }

                        category = unique(category);

                        var result_tmp = [];
                        //补充数组中没有的值
                        for(var i=0;i<result.length;i++){
                            var tmp = {};
                            for (var j = 0;j < result[i].data.length ; j++) {
                                tmp[result[i].data[j].name] = result[i].data[j].value;
                            };
                            result[i]['list'] = tmp;
                        }

                        for(var i=0;i<result.length;i++){
                            var tmp = result[i].list;
                            for(var j=0;j<category.length;j++){
                                if(tmp[category[j]] == undefined){
                                    result[i].list[category[j]] = 0;
                                }
                            }
                        }

                        var total_tmp = [];

                        for(var i=0;i<result.length;i++){
                            var tmp = [];

                            for (var j = 0; j < category.length; j++) {
                                tmp.push(result[i].list[category[j]]);

                                if(total_tmp[j] == undefined){
                                    total_tmp.push(result[i].list[category[j]])
                                }else{
                                    total_tmp[j] += result[i].list[category[j]];
                                }
                            };

                            series.push({'name':result[i].name,data:tmp});
                        }

                        series.push({'name':'总量',data:total_tmp});


                        //配置highcharts的option选项
                        options.series = series;
                        var chart = new Highcharts.Chart(options);
                        chart.xAxis[0].setCategories(category);
                        chart.redraw();
                    }
                );
            };


            get_ajax_data();
            setInterval(get_ajax_data,this.props.interval ? this.props.interval : 500000);
        },
        render:function(){
            return (
                React.createElement("div", {className: this.props.className, id: this.props.id})
            );
        }
    });
});